let layerIndex;
/**
 * 弹出教师新增/更新对话框
 */
function showTeacherDlg() {
    let title="新增教师"
    $("#btnOK").prop("disabled", false).removeClass("layui-btn-disabled");
    if(id){
        //是编辑
        title="编辑教师"
        $("#formId").css("display","block");
        //读取教师信息，并赋值
        $.ajax({
            url:"/api/teacher/"+id,
            method:"GET"
        }).done(result=>{
            console.log(result)
            //遍历result对象并将值填充到表单中
            $.each(result,function(key,value){
                //修改选择器，确保选择的是#teaForm内的字段
                var field =$('#teacherForm [name="'+ key +'"]');

                if(field.is(':radio')){
                    field.filter('[value="'+value+'"]').prop('checked',true)
                }else if(field.is(':checkbox')){
                    field.prop('checked',value==="yes")
                }else{
                    field.val(value);
                }
            });
        })
    }else{
        //是新增
        $("#teacherForm")[0].reset();
        $("#formId").css("display","none")
    }
    layerIndex=layer.open({
        type: 1,
        title:title,
        area: ['520px', 'auto'],
        content: $('#teacherForm')//捕获层
    });
}
function getSearchCondition(){

    let formData={};
    $('#queryForm').find('input,select').each(function(){
        let name=$(this).attr('name');
        let value=$(this).val();  //

        //
        if(name && value){
            formData[name] = value;
        }
    });
    return formData;

}
layui.use(function () {
    //验证表单是否合法
    layui.form.on('submit(teacher-dlg)',function(data){
        event.preventDefault();//阻止表单默认提交
        commitTeacherDlg();
    })
    //(2)表格初始化
    const table =layui.table;
    let teacher = getSearchCondition();

    //创建渲染实例
    table.render({
        elem: '#teacher',
        url: "/api/teacher/getbypage", //此处为静态模拟数据，实际使用时需换成真实接口

        method: "POST",
        contentType: "application/json", //确保以json格式发送
        where: {"data": teacher},

        page: true,
        cols: [[
            {type: 'checkbox', fixed: 'left'},
            {filed: 'id', fixed: 'left', width: 80, title: 'id', sort: true},
            {filed: 'name', title: '姓名'},
            {
                filed: 'tno',
                title: '教工号',

                width: 150,
            },
            {
                filed: 'sex', width: 80, title: '性别', sort: true,
                templet: d => d.sex === 1 ? '男' : (d.sex === 2 ? '女' : '未知'),

            },

            {filed: 'age', width: 100, title: '年龄', sort: true},

            {filed: 'right', title: '操作', width: 134, minWidth: 125, templet: '#editTemplate'},

        ]],
        done: function (rs) {
            //console.log(rs)
        }
    })
    //触发单元格工具事件
    table.on('tool(teacher)', function (obj){

        var data=obj.data;
        if(obj.event==='edit'){
            $("#btnOk").prop("disabled",false).removeClass("layui-btn-disabled");

            //数据填充表单
            $.each(data,function(key,value){
                //修改选择器，确保选择的是#teachForm内的字段
                var field=$('#teacherForm [name="' + key + '"]');
                if(field.is(':radio')){
                    field.filter('[value="'+value+'"]').prop('checked',true);
                    //选中对应的单选按钮
                }
                else if(field.is(':checkbox')){
                    field.prop('checked',value ==="yes");//选中复选框
                }
                else{
                    field.val(value);//填充文本框或其他字段
                }
            });

            layerIndex=layer.open({
                title:'编辑 - id:'+data.id,
                type:1,
                area:['80%','80%'],
                content:$("#teacherForm")
            });
        }
    });
});
function Search(){
    let teacher = getSearchCondition();

    const table = layui.table;
    table.reloadData("teacher", {
        where: {data:teacher}
    });
    console.log("where condition:"+JSON.stringify(teacher));
}

function deleteConfirm(){
    const table = layui.open();
    //
    const checkStatus = table.checkStatus('teacher');

    console.log(checkStatus);
}
function commitTeacherDlg() {

    let id = $("#id").val()
    let formData = $("#teacherForm").serialize();
    if (id != null && id != " ") {
        //更新学生
        $.ajax({
            url: "/api/teacher/update",
            method: "PUT",
            data: formData
        }).done(result => {
            console.log(result);
            if (result.id) {
                //读取并刷新原来的教师列表
                loadTeacherList();
                //关闭弹出层
                console.log("add success!")
                if (layerIndex)
                    layer.close(layerIndex)
            }
        }).fail((jqXHR, textStatus, errorThrown) => {
            console.error("Request failed:" + textStatus + "-" + errorThrown);
            //处理错误逻辑
            alert("An error occurred. Please try again.");
        });

    } else {
        //验证表单是否合法
        //将表单数据发送到服务器的insert中，把提交按钮变灰
        $.ajax({
            url: "/api/teacher/add",
            method: "POST",
            data: formData
        }).done(result => {
            console.log(result);
            if (result.id) {
                //读取并刷新原来的教师列表
                loadTeacherList();
                //关闭弹出层
                console.log("add success!")
                if (layerIndex)
                    layer.close(layerIndex)
            }
        }).fail((jqXHR, textStatus, errorThrown) => {
            console.error("Request failed:" + textStatus + "-" + errorThrown);
            //处理错误逻辑
            alert("An error occurred. Please try again.");
        });
    }
    $("#btnOk").prop("disabled", true);

}
function deleteById(id){
    layer.confirm('确定要删除？', {icon: 3}, function(){
        $.ajax({
            url:"/api/teacher/delete/"+id,
            method:"DELETE"
        }).done(result=>{
            loadTeacherList();
        })
        layer.closeAll();
    }, function(){

    });
}

